package com.agu.mgt.sys.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.agu.common.annotation.SysLog;
import com.agu.entity.sys.SysRoleEntity;
import com.agu.entity.sys.SysUserEntity;
import com.agu.mgt.sys.service.SysRoleService;
import com.agu.mgt.sys.service.SysUserRoleService;
import com.agu.mgt.sys.service.SysUserService;
import com.agu.result.Result;
import com.agu.result.ResultGenerator;
import com.agu.utils.CompareUtils;
import com.agu.utils.Constant;
import com.agu.utils.Query;
import com.agu.utils.ShiroUtils;
import com.agu.utils.validator.Assert;
import com.agu.utils.validator.ValidatorUtils;
import com.agu.utils.validator.group.AddGroup;
import com.agu.utils.validator.group.UpdateGroup;
import com.github.pagehelper.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 系统用户
 * 
 */
@RestController
@Api("用户")
@RequestMapping("sysuser")
public class SysUserController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleService sysRoleService;
	/**
	 * 所有用户列表å
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sysuser:list")
	public Result list(@RequestBody Map params){
		//只有超级管理员，才能查看所有管理员列表
		if(getUserId() != Constant.SUPER_ADMIN){
			params.put("createUserId", getUserId());
		}
		//查询列表数据
		Query query = new Query(params);
		Page<SysUserEntity> userList = sysUserService.queryPageList(query);
		int total = (int)userList.getTotal();
		return ResultGenerator.successPage(userList);
	}
	
	/**
	 * 角色列表
	 */
	@RequestMapping("/roles")
	@RequiresPermissions("sysuser:list")
	public Result select() {
		Map<String, Object> map = new HashMap<>();
		// 如果不是超级管理员，则只查询自己所拥有的角色列表
		if (getUserId() != Constant.SUPER_ADMIN) {
			map.put("createUserId", getUserId());
		}
		
		map.put("plat", 1);
		
		List<SysRoleEntity> list = sysRoleService.queryList(map);

		return ResultGenerator.successData(list);
	}
	
	/**
	 * 获取登录的用户信息
	 */
	@RequestMapping("/info")
	public Result info(){
		Map map = new HashMap();
		map.put("user", getUser());
		return ResultGenerator.successData(map);
	}
	
	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@RequestMapping("/password")
	public Result password(String password, String newPassword){
		Assert.isBlank(newPassword, "新密码不为能空");
		
		//sha256加密
		password = new Sha256Hash(password).toHex();
		//sha256加密
		newPassword = new Sha256Hash(newPassword).toHex();
				
		//更新密码
		int count = sysUserService.updatePassword(getUserId(), password, newPassword);
		if(count == 0){
			return ResultGenerator.fail("原密码不正确");
		}
		
		//退出
		ShiroUtils.logout();
		
		return ResultGenerator.success("修改密码");
	}
	
	/**
	 * 用户信息
	 */
	@RequestMapping("/info/{userId}")
	@RequiresPermissions("sysuser:info")
	public Result info(@PathVariable("userId") Long userId){
		SysUserEntity user = sysUserService.queryObject(userId);
		user.setPassword("");
		//获取用户所属的角色列表
		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		user.setRoleIdList(roleIdList);
		
		return ResultGenerator.successData(user);
	}
	
	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@RequestMapping("/save")
	@RequiresPermissions("sysuser:save")
	public Result save(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, AddGroup.class);
		
		user.setCreateUserId(getUserId());
		sysUserService.save(user);

		//处理日志
		Map<String,String> cmap = new HashMap<String,String>();
		 cmap.put("userId","ID");
		 cmap.put("userName","用户名");
		 cmap.put("email","邮箱");
		 cmap.put("mobile","手机号");
		 cmap.put("userType","用户类别");
		 cmap.put("name","姓名");
		 cmap.put("status","状态");

		String remark = CompareUtils.getObjectRemark(user, cmap);
		return ResultGenerator.success("保存成功").setRemark(remark);
	}
	
	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@RequestMapping("/update")
	@RequiresPermissions("sysuser:update")
	public Result update(@RequestBody SysUserEntity user){
		SysUserEntity user1 = sysUserService.queryObject(user.getUserId());
		
		ValidatorUtils.validateEntity(user, UpdateGroup.class);
		
		user.setCreateUserId(getUserId());
		sysUserService.update(user);
		//处理日志
		Map<String,String> cmap = new HashMap<String,String>();
		 cmap.put("userId","ID");
		 cmap.put("userName","用户名");
		 cmap.put("email","邮箱");
		 cmap.put("mobile","手机号");
		 cmap.put("userType","用户类别");
		 cmap.put("name","姓名");
		 cmap.put("status","状态");
		String remark = CompareUtils.getTwoObjectRemark(user1, user, cmap);
		
		return ResultGenerator.success("修改成功").setRemark(remark);
	}
	
	/**
	 * 删除
	 */
	@SysLog("删除用户")
	@RequestMapping("/delete/{userId}")
	@ApiOperation(value = "删除", notes = "说明")
	@RequiresPermissions("sysuser:delete")
	public Result delete(@PathVariable("userId") Long userId) {
	 
	    	if (userId == null) {
			return ResultGenerator.fail("缺少参数");
		}
	
		SysUserEntity sysUser = sysUserService.queryObject(userId);
	
		sysUserService.delete(userId);
		
		//处理日志
		Map<String,String> cmap = new HashMap<String,String>();
		 cmap.put("userId","ID");
		 cmap.put("userName","用户名");
		 cmap.put("email","邮箱");
		 cmap.put("mobile","手机号");
		 cmap.put("userType","用户类别");
		 cmap.put("name","姓名");
		 cmap.put("status","状态");
		String remark = CompareUtils.getObjectRemark(sysUser, cmap);
		return ResultGenerator.success("删除成功").setRemark(remark);
	}
	
	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@RequestMapping("/deletes")
	@RequiresPermissions("sysuser:delete")
	public Result deletes(@RequestBody Long[] userIds){
		if(ArrayUtils.contains(userIds, 1L)){
			return ResultGenerator.fail("系统管理员不能删除");
		}
		
		if(ArrayUtils.contains(userIds, getUserId())){
			return ResultGenerator.fail("当前用户不能删除");
		}
		
		sysUserService.deleteBatch(userIds);
		
		return ResultGenerator.success("删除成功");
	}
}
